package com.example.gkcircle.fragment.love;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.example.gkcircle.App;
import com.example.gkcircle.BaseFragment;
import com.example.gkcircle.MainActivity;
import com.example.gkcircle.R;
import com.example.gkcircle.adapter.LoveAdapter;
import com.example.gkcircle.adapter.WishAdapter;
import com.example.gkcircle.bean.Love;
import com.example.gkcircle.bean.Wish;
import com.example.gkcircle.db.DBUtil;
import com.example.gkcircle.utils.DateUtil;
import com.example.gkcircle.utils.ToastFactory;

import java.util.ArrayList;
import java.util.List;


/**
 * * 表白墙
 * * @author ZhouHua
 * created at 15/12/21 上午12:54
 */
public class LoveWallFragment extends BaseFragment implements AbsListView.OnScrollListener{



    private SwipeRefreshLayout mSwipe;
    private ListView mListView;
    private LoveAdapter mAdapter;
    private View mHeaderView;
    private View mFooterView;

    private int currentPage = 0;
    private final int maxDataCount = 10;
    private boolean isRefreshing;

    private static LoveWallFragment instance;

    public static LoveWallFragment getInstance() {
        if (instance == null) instance = new LoveWallFragment();
        return instance;
    }

    @Override
    protected int setLayout() {
        return R.layout.love_love_wall_fragment;
    }

    @Override
    protected void initView(View view) {
        mSwipe=(SwipeRefreshLayout)view.findViewById(R.id.love_love_swipe);
        mListView=(ListView)view.findViewById(R.id.love_love_listview);
    }

    @Override
    protected void initListener() {
        mSwipe.setColorSchemeColors(getResources().getColor(R.color.main), getResources().getColor(R.color.love), getResources().getColor(R.color.wish));
        currentPage = 0;
        mListView.setOnScrollListener(this);
        //下拉刷新
        mSwipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (!isRefreshing) {
                    currentPage = 0;
                    isRefreshing = true;
                    setData();
                }
            }
        });
    }

    //上拉加载
    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        switch (scrollState) {
            case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                if (mListView.getLastVisiblePosition() == (mListView.getCount() - 1)) {
                    currentPage++;
                    setData();
                }
                break;
        }
    }
    @Override
    protected void setData() {
        mSwipe.setRefreshing(true);
        //获取数据
        getData(currentPage, new IGetDataListener() {
            @Override
            public void complete(List<AVObject> list) {
                if (null == list) {
                    currentPage--;
                    return;
                }
                if (App.mLoveList == null) {
                    App.mLoveList = new ArrayList<Love>();
                } else {
                    if (isRefreshing) App.mLoveList.clear();
                }
                for (int i = 0; i < list.size(); i++) {
                    Love love = new Love();
                    love.setUser(list.get(i).getAVUser("user"));
                    love.setContent(list.get(i).get("content").toString());
                    love.setCreatedAt(DateUtil.getLastMinTime(list.get(i).getDate("createdAt").getTime()));
                    love.setObjectId(list.get(i).getObjectId());
                    love.setAnonymous(list.get(i).getBoolean("anonymous"));
                    love.setCommentCount(list.get(i).getAVObject("like").getInt("likeCount"));
                    love.setCommentCountObjectId(list.get(i).getAVObject("like").getObjectId());
                    App.mLoveList.add(love);
                }
                if (mAdapter != null) {
                    mAdapter.notifyDataSetChanged();
                    mSwipe.setRefreshing(false);
                    isRefreshing = false;
                    mSwipe.setEnabled(true);
                    return;
                }
                //add headerView
                if(mHeaderView==null || mFooterView==null){
                    mHeaderView= LayoutInflater.from(getActivity()).inflate(R.layout.divider_header_footer,null);
                    mFooterView=LayoutInflater.from(getActivity()).inflate(R.layout.divider_header_footer,null);
                    mListView.addHeaderView(mHeaderView, null, false);
                    mListView.addFooterView(mFooterView, null, false);
                }
                mSwipe.setRefreshing(false);
                mAdapter=new LoveAdapter(getActivity(),App.mLoveList);
                mListView.setAdapter(mAdapter);
            }
        });
    }

    //获取数据
    public IGetDataListener getDataListener;

    private interface IGetDataListener {
        void complete(List<AVObject> list);
    }

    private void getData(int currentPage, final IGetDataListener getDataListener) {
        this.getDataListener = getDataListener;
        AVQuery<AVObject> query = new AVQuery<>("Love");
        query.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE);
        query.setLimit(maxDataCount);
        query.setSkip(maxDataCount * currentPage);
        query.orderByDescending("createdAt");
        query.include("user");
        query.include("like");
        query.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> list, AVException e) {
                if (e == null) {
                    if (list.size() > 0) {
                        if (dataFlag) getDataListener.complete(list);
                        else return;
                    } else {
                        if (dataFlag) getDataListener.complete(null);
                        else return;
                        mSwipe.setRefreshing(false);
                        ToastFactory.getToast(getActivity(), getResources().getString(R.string.no_more_data)).show();
                    }
                } else {
                    mSwipe.setRefreshing(false);
                    ToastFactory.getToast(getActivity(), getResources().getString(R.string.connection_error)).show();
                }
            }
        });
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        if (MainActivity.mFloatingActionButton != null) {
            if (MainActivity.firstVisiableItem > firstVisibleItem) {
                MainActivity.firstVisiableItem = firstVisibleItem;
            }

            if (MainActivity.firstVisiableItem == firstVisibleItem) {
                MainActivity.mFloatingActionButton.setVisibility(View.VISIBLE);
                MainActivity.mTabbar.setVisibility(View.VISIBLE);
            } else {
                MainActivity.mFloatingActionButton.setVisibility(View.GONE);
                MainActivity.mTabbar.setVisibility(View.GONE);
                MainActivity.firstVisiableItem = firstVisibleItem - 1;
                if (MainActivity.mFloatingActionMenu.isOpen()) {
                    MainActivity.mFloatingActionMenu.close(true);
                }
            }
        }
    }
}

